package com.lazyben.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lazyben.model.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

public class MessageUtils {
    public static Message parseMessage(Object msg) throws JsonProcessingException {
        ByteBuf in = (ByteBuf) msg;
        int readableBytes = in.readableBytes();
        byte[] bytes = new byte[readableBytes];
        in.readBytes(bytes);
        String msgStr = new String(bytes, StandardCharsets.UTF_8);
        Message message = new ObjectMapper().readValue(msgStr, Message.class);
        return message;
    }

    public static ByteBuf messageWrapper(Message message) throws JsonProcessingException {
        String msg = new ObjectMapper().writeValueAsString(message) + "\r\n";
        return Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
    }
}
